<template>
  <a-form class="login-form" :model="formData" :rules="rules">
    <a-form-item class="login-form__form-item" v-bind="validateInfos.username">
      <a-input
        size="large"
        v-model:value="formData.username"
        placeholder="请输入用户名"
      >
        <template #prefix>
          <user-outlined style="color: rgba(0, 0, 0, 0.25)" />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item class="login-form__form-item" v-bind="validateInfos.password">
      <a-input-password
        size="large"
        v-model:value="formData.password"
        placeholder="请输入密码"
        @press-enter="onLogin"
      >
        <template #prefix>
          <lock-outlined style="color: rgba(0, 0, 0, 0.25)" />
        </template>
      </a-input-password>
    </a-form-item>
    <a-form-item class="login-form__form-item">
      <a-button
        size="large"
        class="login-form__login-btn"
        type="primary"
        @click="onLogin"
        :loading="loading"
        >登录</a-button
      >
    </a-form-item>
  </a-form>
</template>

<script setup lang="ts">
import type { LoginFormParams } from '@/store/account/actions'
import type { ValidateErrorEntity } from 'ant-design-vue/lib/form/interface'
import { Form } from 'ant-design-vue'
import { ValidationRule } from 'ant-design-vue/lib/form/Form'
import { ref } from 'vue'
const { useForm } = Form

const props = defineProps<{
  formData: LoginFormParams
  loading: boolean
}>()

const emits = defineEmits<{
  (e: 'login'): void
}>()

const rules = ref<Record<keyof LoginFormParams, ValidationRule[]>>({
  username: [{ required: true, message: '用户名是必填项', trigger: 'blur' }],
  password: [{ required: true, message: '密码是必填项', trigger: 'blur' }],
})
const { validate, validateInfos } = useForm(props.formData, rules)

const onLogin = () => {
  validate()
    .then(async () => {
      emits('login')
    })
    .catch((error: ValidateErrorEntity<LoginFormParams>) => {
      console.log('error', error)
    })
}
</script>

<style lang="scss" scoped>
@include b(login-form) {
  display: flex;
  flex-direction: column;
  width: 328px;
  @include e(form-item) {
    margin-top: 12px;
    width: 100%;
  }
  @include e(login-btn) {
    width: 100%;
  }
}
</style>
